/**
 * React Hooks 深入学习 - useState 和 useReducer
 * 演示场景：聊天消息管理
 */

import React, { useState, useReducer, useRef } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
} from 'react-native';

// ============================================
// 类型定义
// ============================================
interface Message {
  id: string;
  text: string;
  timestamp: Date;
  sender: 'user' | 'bot';
  status: 'sending' | 'sent' | 'failed';
}

// useReducer 的 Action 类型
type ChatAction =
  | { type: 'ADD_MESSAGE'; payload: Message }
  | {
      type: 'UPDATE_MESSAGE_STATUS';
      payload: { id: string; status: Message['status'] };
    }
  | { type: 'DELETE_MESSAGE'; payload: string }
  | { type: 'CLEAR_ALL' }
  | { type: 'MARK_ALL_READ' };

interface ChatState {
  messages: Message[];
  unreadCount: number;
}

// ============================================
// useReducer 实现 - 复杂状态管理
// ============================================
const chatReducer = (state: ChatState, action: ChatAction): ChatState => {
  switch (action.type) {
    case 'ADD_MESSAGE':
      return {
        ...state,
        messages: [...state.messages, action.payload],
        unreadCount:
          action.payload.sender === 'bot'
            ? state.unreadCount + 1
            : state.unreadCount,
      };

    case 'UPDATE_MESSAGE_STATUS':
      return {
        ...state,
        messages: state.messages.map(msg =>
          msg.id === action.payload.id
            ? { ...msg, status: action.payload.status }
            : msg,
        ),
      };

    case 'DELETE_MESSAGE':
      return {
        ...state,
        messages: state.messages.filter(msg => msg.id !== action.payload),
      };

    case 'CLEAR_ALL':
      return {
        messages: [],
        unreadCount: 0,
      };

    case 'MARK_ALL_READ':
      return {
        ...state,
        unreadCount: 0,
      };

    default:
      return state;
  }
};

// ============================================
// 主组件
// ============================================
export default function TestReactHook1() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>React Hooks 学习演示</Text>
      <Text style={styles.subtitle}>useState vs useReducer</Text>

      {/* useState 示例 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>📝 使用 useState (简单状态)</Text>
        <ChatWithUseState />
      </View>

      {/* useReducer 示例 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>🔧 使用 useReducer (复杂状态)</Text>
        <ChatWithUseReducer />
      </View>
    </View>
  );
}

// ============================================
// useState 实现 - 简单聊天
// ============================================
function ChatWithUseState() {
  // 多个独立的 useState
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputText, setInputText] = useState('');
  const [messageCount, setMessageCount] = useState(0);

  // 创建 ScrollView 的引用，用于自动滚动
  const scrollViewRef = useRef<ScrollView>(null);

  const sendMessage = () => {
    if (!inputText.trim()) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      text: inputText,
      timestamp: new Date(),
      sender: 'user',
      status: 'sending',
    };

    // 添加消息
    setMessages([...messages, newMessage]);
    setMessageCount(messageCount + 1);
    setInputText('');

    // 模拟发送成功
    setTimeout(() => {
      setMessages(prevMessages =>
        prevMessages.map(msg =>
          msg.id === newMessage.id ? { ...msg, status: 'sent' } : msg,
        ),
      );

      // 模拟机器人回复
      const botMessage: Message = {
        id: (Date.now() + 1).toString(),
        text: `收到你的消息: "${newMessage.text}"`,
        timestamp: new Date(),
        sender: 'bot',
        status: 'sent',
      };
      setMessages(prevMessages => [...prevMessages, botMessage]);
      setMessageCount(prevCount => prevCount + 1);
    }, 500);
  };

  const clearMessages = () => {
    setMessages([]);
    setMessageCount(0);
  };

  return (
    <View style={styles.chatContainer}>
      <View style={styles.statsBar}>
        <Text style={styles.statsText}>消息数: {messageCount}</Text>
        <TouchableOpacity onPress={clearMessages} style={styles.clearButton}>
          <Text style={styles.clearButtonText}>清空</Text>
        </TouchableOpacity>
      </View>

      <ScrollView
        ref={scrollViewRef}
        style={styles.messageList}
        onContentSizeChange={() =>
          scrollViewRef.current?.scrollToEnd({ animated: true })
        }
      >
        {messages.map(msg => (
          <MessageBubble key={msg.id} message={msg} />
        ))}
      </ScrollView>

      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          value={inputText}
          onChangeText={setInputText}
          placeholder="输入消息..."
          onSubmitEditing={sendMessage}
        />
        <TouchableOpacity onPress={sendMessage} style={styles.sendButton}>
          <Text style={styles.sendButtonText}>发送</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

// ============================================
// useReducer 实现 - 复杂聊天
// ============================================
function ChatWithUseReducer() {
  // 使用 useReducer 管理复杂状态
  const [state, dispatch] = useReducer(chatReducer, {
    messages: [],
    unreadCount: 0,
  });
  const [inputText, setInputText] = useState('');

  // 创建 ScrollView 的引用，用于自动滚动
  const scrollViewRef = useRef<ScrollView>(null);

  const sendMessage = () => {
    if (!inputText.trim()) return;

    const newMessage: Message = {
      id: Date.now().toString(),
      text: inputText,
      timestamp: new Date(),
      sender: 'user',
      status: 'sending',
    };

    // 通过 dispatch 触发状态更新
    dispatch({ type: 'ADD_MESSAGE', payload: newMessage });
    setInputText('');

    // 模拟发送成功
    setTimeout(() => {
      dispatch({
        type: 'UPDATE_MESSAGE_STATUS',
        payload: { id: newMessage.id, status: 'sent' },
      });

      // 模拟机器人回复
      const botMessage: Message = {
        id: (Date.now() + 1).toString(),
        text: `我是机器人，你说: "${newMessage.text}"`,
        timestamp: new Date(),
        sender: 'bot',
        status: 'sent',
      };
      dispatch({ type: 'ADD_MESSAGE', payload: botMessage });
    }, 500);
  };

  const deleteMessage = (id: string) => {
    dispatch({ type: 'DELETE_MESSAGE', payload: id });
  };

  const clearAll = () => {
    dispatch({ type: 'CLEAR_ALL' });
  };

  const markAllRead = () => {
    dispatch({ type: 'MARK_ALL_READ' });
  };

  return (
    <View style={styles.chatContainer}>
      <View style={styles.statsBar}>
        <Text style={styles.statsText}>
          消息数: {state.messages.length} | 未读: {state.unreadCount}
        </Text>
        <View style={styles.buttonGroup}>
          {state.unreadCount > 0 && (
            <TouchableOpacity onPress={markAllRead} style={styles.readButton}>
              <Text style={styles.readButtonText}>标记已读</Text>
            </TouchableOpacity>
          )}
          <TouchableOpacity onPress={clearAll} style={styles.clearButton}>
            <Text style={styles.clearButtonText}>清空</Text>
          </TouchableOpacity>
        </View>
      </View>

      <ScrollView
        ref={scrollViewRef}
        style={styles.messageList}
        onContentSizeChange={() =>
          scrollViewRef.current?.scrollToEnd({ animated: true })
        }
      >
        {state.messages.map(msg => (
          <MessageBubbleWithDelete
            key={msg.id}
            message={msg}
            onDelete={() => deleteMessage(msg.id)}
          />
        ))}
      </ScrollView>

      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          value={inputText}
          onChangeText={setInputText}
          placeholder="输入消息 (长按删除)..."
          onSubmitEditing={sendMessage}
        />
        <TouchableOpacity onPress={sendMessage} style={styles.sendButton}>
          <Text style={styles.sendButtonText}>发送</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

// ============================================
// 消息气泡组件
// ============================================
function MessageBubble({ message }: { message: Message }) {
  const isUser = message.sender === 'user';

  return (
    <View
      style={[
        styles.messageBubble,
        isUser ? styles.userBubble : styles.botBubble,
      ]}
    >
      <Text
        style={[styles.messageText, isUser ? styles.userText : styles.botText]}
      >
        {message.text}
      </Text>
      <Text style={styles.messageTime}>
        {message.timestamp.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
        })}
        {message.status === 'sending' && ' 发送中...'}
        {message.status === 'failed' && ' 失败'}
      </Text>
    </View>
  );
}

function MessageBubbleWithDelete({
  message,
  onDelete,
}: {
  message: Message;
  onDelete: () => void;
}) {
  const isUser = message.sender === 'user';

  return (
    <TouchableOpacity
      onLongPress={onDelete}
      style={[
        styles.messageBubble,
        isUser ? styles.userBubble : styles.botBubble,
      ]}
    >
      <Text
        style={[styles.messageText, isUser ? styles.userText : styles.botText]}
      >
        {message.text}
      </Text>
      <Text style={styles.messageTime}>
        {message.timestamp.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
        })}
        {message.status === 'sending' && ' 发送中...'}
        {message.status === 'failed' && ' 失败'}
      </Text>
    </TouchableOpacity>
  );
}

// ============================================
// 样式
// ============================================
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 5,
    color: '#333',
  },
  subtitle: {
    fontSize: 14,
    textAlign: 'center',
    marginBottom: 20,
    color: '#666',
  },
  section: {
    flex: 1,
    marginHorizontal: 10,
    marginBottom: 10,
    backgroundColor: '#fff',
    borderRadius: 10,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    padding: 12,
    backgroundColor: '#4a90e2',
    color: '#fff',
  },
  chatContainer: {
    flex: 1,
  },
  statsBar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#f8f8f8',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  statsText: {
    fontSize: 12,
    color: '#666',
  },
  buttonGroup: {
    flexDirection: 'row',
    gap: 8,
  },
  clearButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: '#ff6b6b',
    borderRadius: 4,
  },
  clearButtonText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '600',
  },
  readButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: '#51cf66',
    borderRadius: 4,
  },
  readButtonText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '600',
  },
  messageList: {
    flex: 1,
    padding: 10,
  },
  messageBubble: {
    maxWidth: '80%',
    padding: 10,
    borderRadius: 12,
    marginBottom: 8,
  },
  userBubble: {
    alignSelf: 'flex-end',
    backgroundColor: '#4a90e2',
  },
  botBubble: {
    alignSelf: 'flex-start',
    backgroundColor: '#e0e0e0',
  },
  messageText: {
    fontSize: 14,
  },
  userText: {
    color: '#fff',
  },
  botText: {
    color: '#333',
  },
  messageTime: {
    fontSize: 10,
    marginTop: 4,
    opacity: 0.7,
  },
  inputContainer: {
    flexDirection: 'row',
    padding: 10,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
  },
  input: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 8,
    marginRight: 8,
    fontSize: 14,
  },
  sendButton: {
    backgroundColor: '#4a90e2',
    borderRadius: 20,
    paddingHorizontal: 20,
    justifyContent: 'center',
  },
  sendButtonText: {
    color: '#fff',
    fontWeight: '600',
    fontSize: 14,
  },
});
